package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	
	import org.etherframework.controller.ReactiveCommand;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	
	public class SaveAllDocumentsCommand extends ReactiveCommand
	{
		private var _editorModel:EditorModuleModel;
		private var _editorController:IEditorController;
		
		public function SaveAllDocumentsCommand(editorModel:EditorModuleModel, 
												editorController:IEditorController)
		{
			_editorModel = editorModel;
			_editorController = editorController;
			
			markAsInitialized();
		}
		
		override public function observable():IObservable
		{
			return Observable.defer(function():IObservable
			{
				return Observable.fromArray(_editorModel.openedDocuments.source.reverse())
				.concatMany(function(document:DocumentVO):IObservable
				{
					return (document.id) ?
					_editorController.getSaveDocumentCommand(document).observable() :
					_editorController.getSaveAsDocumentCommand(document).observable(); 
				}).takeLast(1).mapMany(function():IObservable
				{
					return _editorController.getRefreshAllCommand().observable();
				});
			});
		}
	}
}